package com.mingqijia.gassafety.statistics.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.redis.LatestLog;
import com.mingqijia.gassafety.db.entity.vo.*;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.DateFormatUtil;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.statistics.request.*;
import com.mingqijia.gassafety.db.entity.vo.IndustryUnderUserListVo;
import com.mingqijia.gassafety.statistics.response.*;
import com.mingqijia.gassafety.statistics.response.IndustryConsumerResponse;
import com.mingqijia.gassafety.statistics.service.IndustryScreenService;
import com.mingqijia.gassafety.webserver.dto.AdInfoDTO;
import com.mingqijia.gassafety.webserver.request.CustDetailRequest;
import com.mingqijia.gassafety.webserver.response.*;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.webserver.utils.CoordinatesTransitionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.*;
import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;
import static com.mingqijia.gassafety.webserver.constant.DeviceConstant.VALVE_WORK_STATUS_BROKEN;

@Slf4j
@Service
public class IndustryScreenServiceImpl implements IndustryScreenService {

    @Value(value = "${asst.workOrder.doamin.url}")
    String workOrderUrl;

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private DtuMapper dtuMapper;

    @Autowired
    OrganizationService organizationService;

    @Autowired
    FieldTemplateService fieldTemplateService;

    @Autowired
    HttpUtil httpUtil;

    @Autowired
    ConfigureHolder holder;

    @Autowired
    private WorkOrderHistoryMapper workOrderHistoryMapper;

    @Autowired
    CompanyService companyService;

    @Autowired
    private HistoryAlarmMapper historyAlarmMapper;

    @Autowired
    private HistoryBrokenMapper historyBrokenMapper;

    @Autowired
    private ReceiverValveService receiverValveService;

    @Autowired
    ConsumerService consumerService;

    @Autowired
    LatestLogService latestLogService;

    @Autowired
    CockpitService cockpitService;

    @Autowired
    DictionaryService dictionaryService;

    @Resource
    ConsumerLocationService consumerLocationService;

    @Resource
    FunctionAreaService functionAreaService;

    @Resource
    FieldTemplateMapper fieldTemplateMapper;

    @Resource
    UserPermissionService userPermissionService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    @Override
    public Integer underUserSum(IndustryScreenReq screenReq) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (screenReq == null) {
            screenReq = new IndustryScreenReq();
            screenReq.setSpId(spId);
        }
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spId,ApplicationUtils.getUserId());
        Integer userSum = consumerMapper.getUnderUserSum(spId, screenReq.getIndustryType(), screenReq.getAdCode(), screenReq.getTownCode(), screenReq.getBusinessAreaCode(),
                userFuncCodePermission.getFuncCodes());
        return userSum;
    }

    @Override
    public IndustryDeviceRunningCaseResp deviceRunningCase(IndustryScreenReq screenReq) {
        String spId = ApplicationUtils.getWorkingSpId();
        if (screenReq == null) {
            screenReq = new IndustryScreenReq();
            screenReq.setSpId(spId);
        }
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spId,ApplicationUtils.getUserId());
        IndustryDeviceRunningCaseResp deviceRunningCaseResp = new IndustryDeviceRunningCaseResp();
        DeviceRunningCaseVo runningCaseVo = dtuMapper.deviceRunningCase(spId, screenReq.getIndustryType(), screenReq.getAdCode(), screenReq.getTownCode(), screenReq.getBusinessAreaCode(),
                userFuncCodePermission.getFuncCodes());
        if (runningCaseVo != null) {
            //探头数量
            IndustryDeviceRunningSumResp runningSumResp = new IndustryDeviceRunningSumResp();
            runningSumResp.setOffLineSum(runningCaseVo.getProbeOffLineSum());
            runningSumResp.setNormalSum(runningCaseVo.getProbeNormalSum());
            runningSumResp.setAlarmSum(runningCaseVo.getProbeAlarmSum());
            runningSumResp.setBrokenSum(runningCaseVo.getProbeBrokenSum());
            deviceRunningCaseResp.setProbe(runningSumResp);
            //控制器数量
            IndustryDeviceRunningSumResp sumResp = new IndustryDeviceRunningSumResp();
            sumResp.setOffLineSum(runningCaseVo.getControllerOffLineSum());
            sumResp.setNormalSum(runningCaseVo.getControllerNormalSum());
            sumResp.setAlarmSum(runningCaseVo.getControllerAlarmSum());
            sumResp.setBrokenSum(runningCaseVo.getControllerBrokenSum());
            deviceRunningCaseResp.setController(sumResp);
        } else {
            //探头数量
            IndustryDeviceRunningSumResp runningSumResp = new IndustryDeviceRunningSumResp();
            runningSumResp.setOffLineSum(0);
            runningSumResp.setNormalSum(0);
            runningSumResp.setAlarmSum(0);
            runningSumResp.setBrokenSum(0);
            deviceRunningCaseResp.setProbe(runningSumResp);
            //控制器数量
            IndustryDeviceRunningSumResp sumResp = new IndustryDeviceRunningSumResp();
            sumResp.setOffLineSum(0);
            sumResp.setNormalSum(0);
            sumResp.setAlarmSum(0);
            sumResp.setBrokenSum(0);
            deviceRunningCaseResp.setController(sumResp);
        }
        return deviceRunningCaseResp;
    }

    /**
     * 工单情况
     * @param req
     * @return
     */
    @Override
    public List<OrderConditionResponse> orderCondition(IndustryScreenOrderConditionReq req) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);

        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        //查询当前企业下的设备id
        List<String> condition = dtuMapper.orderCondition(spId, req.getIndustryType(), req.getAdCode(), req.getTownCode(), req.getBusinessAreaCode(),
                userFuncCodePermission.getFuncCodes());
        //模版1mbp
        String format = DateUtil.format(new Date(), "yyyy-MM-dd");

        //计算日期
        String endDate = DateUtil.format(DateUtil.offsetDay(new Date(), -1), "yyyy-MM-dd");
        String startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -7), "yyyy-MM-dd");

        List<OrderConditionResponse> responses = new ArrayList<>();
        List<OrderConditionResponse> responsesCopy = new ArrayList<>();
        List<WorkOrderHistory> completeList = new ArrayList<>();
        QueryWrapper<WorkOrderHistory> queryWrapper = new QueryWrapper<>();
        QueryWrapper<WorkOrderHistory> queryWrapperUpdate = new QueryWrapper<>();
        LambdaQueryWrapper<WorkOrderHistory> or = queryWrapper.lambda().or();
        LambdaQueryWrapper<WorkOrderHistory> orUpdate = queryWrapperUpdate.lambda().or();
        or.in(WorkOrderHistory::getSpId, spIds).eq(WorkOrderHistory::getIsDeleted, 0);
        orUpdate.in(WorkOrderHistory::getSpId, spIds).eq(WorkOrderHistory::getIsDeleted, 0);
        if (req.getType() == 0) {
            or.like(WorkOrderHistory::getCreatedAt, format);
            orUpdate.like(WorkOrderHistory::getUpdatedAt, format);
        } else {
            or.between(WorkOrderHistory::getCreatedAt, startDate, DateUtil.format(DateUtil.offsetDay(new Date(), 0), "yyyy-MM-dd"));
            orUpdate.between(WorkOrderHistory::getUpdatedAt, startDate, DateUtil.format(DateUtil.offsetDay(new Date(), 0), "yyyy-MM-dd"));
        }
        //工单系统为MBP
        List<WorkOrderHistory> workOrderHistoriesUpdate = new ArrayList<>();
        List<WorkOrderHistory> workOrderHistories = new ArrayList<>();
        if (!CollectionUtils.isEmpty(condition)) {
            or.in(WorkOrderHistory::getDeviceId, condition);
            orUpdate.in(WorkOrderHistory::getDeviceId, condition);
            workOrderHistoriesUpdate = workOrderHistoryMapper.selectList(orUpdate);
            workOrderHistories = workOrderHistoryMapper.selectList(or);
        }

        log.info("orderCondition-or:{}", JSONObject.toJSONString(or));

        if (!CollectionUtil.isEmpty(workOrderHistoriesUpdate)) {
            List<Long> ids = new ArrayList<>();
            workOrderHistories.forEach(workOrderHistory -> {
                ids.add(workOrderHistory.getId());
            });
            for (WorkOrderHistory workOrderHistory : workOrderHistoriesUpdate) {
                if (!ids.contains(workOrderHistory.getId())) {
                    workOrderHistories.add(workOrderHistory);
                }
            }

        }
        log.info("orderCondition-workOrderHistories:{}，workOrderHistoriesUpdate:{}", JSONObject.toJSONString(workOrderHistories),
                JSONObject.toJSONString(workOrderHistoriesUpdate));

        if (CollectionUtil.isEmpty(workOrderHistories) && req.getType() == 0) {
            OrderConditionResponse orderConditionResponse = new OrderConditionResponse();
            orderConditionResponse.setDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
            List<OrderConditionSonsResponse> objects = new ArrayList<>();
            for (int j = 1; j < 4; j++) {
                OrderConditionSonsResponse sons = new OrderConditionSonsResponse();
                sons.setType(j);
                sons.setAppealNum(0);
                sons.setCompleteNum(0);
                objects.add(sons);
            }
            orderConditionResponse.setList(objects);
            responsesCopy.add(orderConditionResponse);
            return responsesCopy;
        }

        workOrderHistories.forEach(workOrderHistory -> {
            workOrderHistory.setCreateDate(DateUtil.format(workOrderHistory.getCreatedAt(), "yyyy-MM-dd"));
            workOrderHistory.setUpdateDate(DateUtil.format(workOrderHistory.getUpdatedAt(), "yyyy-MM-dd"));
        });
        workOrderHistories.forEach(workOrderHistory -> {
            if (workOrderHistory.getHandleStatus() == 1) completeList.add(workOrderHistory);
        });

        Map<String, List<WorkOrderHistory>> collect = workOrderHistories.stream()
                .collect(Collectors.groupingBy(WorkOrderHistory::getCreateDate, Collectors.toList()));
        if (!CollectionUtil.isEmpty(workOrderHistories) && collect.size() > 0  ) {
            collect.forEach((s, aLong) -> {
                int num = 0;
                for (WorkOrderHistory workOrderHistory : aLong) {
                    if (!workOrderHistory.getCreateDate()
                            .equals(workOrderHistory.getUpdateDate()))
                        num = num + 1;
                }
                List<OrderConditionSonsResponse> orderConditionSonsResponses = new ArrayList<>();
                OrderConditionResponse conditionResponse = new OrderConditionResponse();
                for (int i = 1; i < 4; i++) {
                    OrderConditionSonsResponse orderConditionSonsResponse = new OrderConditionSonsResponse();
                    int finalI = i;
                    long appealNum = aLong.stream().filter(workOrderHistory -> {
                        return workOrderHistory.getOrderType() == finalI;
                    }).count();
                    long completeNum = 0L;
                    orderConditionSonsResponse.setType(i);
                    orderConditionSonsResponse.setAppealNum(appealNum);
                    if (!CollectionUtil.isEmpty(completeList)) {
                        for (WorkOrderHistory workOrderHistory : completeList) {
                            if (workOrderHistory.getUpdateDate().equals(s) && workOrderHistory.getOrderType() == finalI)
                                completeNum = completeNum + 1;
                        }
                    }
                    orderConditionSonsResponse.setCompleteNum(completeNum);
                    orderConditionSonsResponses.add(orderConditionSonsResponse);

                }
                conditionResponse.setDate(s);
                conditionResponse.setList(orderConditionSonsResponses);
                responses.add(conditionResponse);
            });
        }
        log.info("orderCondition--responses:{}",JSONObject.toJSONString(responses));
        if (req.getType() >= 1) {
            List<String> days = DateFormatUtil.getDays(startDate, endDate, "yyyy-MM-dd", 1, new ArrayList<>());
            if (!CollectionUtil.isEmpty(days)) {
                for (String day : days) {
                    int i = 0;
                    for (OrderConditionResponse respons : responses) {
                        if (day.equals(respons.getDate())) {
                            responsesCopy.add(respons);
                            i = 1;
                            continue;
                        }
                    }
                    if (i == 0) {
                        OrderConditionResponse orderConditionResponse = new OrderConditionResponse();
                        orderConditionResponse.setDate(day);
                        List<OrderConditionSonsResponse> objects = new ArrayList<>();
                        for (int j = 1; j < 4; j++) {
                            OrderConditionSonsResponse sons = new OrderConditionSonsResponse();
                            sons.setType(j);
                            sons.setAppealNum(0);
                            Long completeNum = 0L;
                            if (!CollectionUtil.isEmpty(completeList)) {
                                for (WorkOrderHistory workOrderHistory : completeList) {
                                    if (workOrderHistory.getUpdateDate().equals(day)
                                            && workOrderHistory.getOrderType() == j)
                                        completeNum = completeNum + 1;
                                }
                            }
                            sons.setCompleteNum(completeNum);
                            objects.add(sons);
                        }
                        orderConditionResponse.setList(objects);
                        responsesCopy.add(orderConditionResponse);
                    }

                }
            }
        } else {
            log.info("orderCondition--responses:{}",JSONObject.toJSONString(responses));
            for (OrderConditionResponse respons : responses) {
                respons.getList().forEach(orderConditionSonsResponse -> {
                    long completeNum=0;
                    if (!CollectionUtil.isEmpty(completeList)
                            &&orderConditionSonsResponse.getCompleteNum()==0) {
                        for (WorkOrderHistory workOrderHistory : completeList) {
                            if (workOrderHistory.getUpdateDate().equals(format)
                                    && workOrderHistory.getOrderType() == orderConditionSonsResponse.getType())
                                completeNum = completeNum + 1;
                        }
                    }
                    orderConditionSonsResponse.setCompleteNum(completeNum+orderConditionSonsResponse.getCompleteNum());

                });

            }
            responsesCopy = responses;
        }
        log.info("orderCondition-responses:{}", JSONObject.toJSONString(responses));
        return responsesCopy;
    }

    @Override
    public ConsumerMapGroupResponse queryCustMapGroupList(IndustryMapGroupRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);

        double zoom = request.getZoom();
        List<ConsumerLocationGroupItemVO> itemVOList = new ArrayList<>();

        Map<String,String> zoomMap = dictionaryService.getFuncAreaZoom(spId);
        if(MapUtils.isEmpty(zoomMap) || ("0".equals(zoomMap.get("city")) && "0".equals(zoomMap.get("district")) && "0".equals(zoomMap.get("street")) )){
            throw new RuntimeException("该企业无需展示聚合数据");
        }

        String level = "street";
        if (!StringUtils.isEmpty(request.getIndustryType()) || !StringUtils.isEmpty(request.getAdCode()) || !StringUtils.isEmpty(request.getTownCode())) {
            itemVOList = dtuMapper.queryConsumerGroupList(spIds, request.getIndustryType(), request.getAdCode(), request.getTownCode(), request.getBusinessAreaCode(),
                    userFuncCodePermission.getFuncCodes());
            if (!StringUtils.isEmpty(request.getTownCode())) {
                level = "street";
            } else if (!StringUtils.isEmpty(request.getAdCode())) {
                level = "district";
            } else {
                level = "city";
            }
        } else {
            List<String> zoomKeys = Arrays.asList("city","district","street");
            for (String key : zoomMap.keySet()) {
                String zoomStr = null==zoomMap.get(key)?"":zoomMap.get(key);
                String[] strArr = zoomStr.split("-");
                if ( zoomKeys.contains(key) && strArr.length == 2 ) {
                    int minZoom = Integer.parseInt(strArr[0]);
                    int maxZoom = Integer.parseInt(strArr[1]);
                    if( zoom >= minZoom && zoom < maxZoom ){
                        level = key;
                        break;
                    }
                }
            }
            itemVOList = dtuMapper.selectConsumerGroupsList(spIds,level,userFuncCodePermission.getFuncCodes());
        }

        ConsumerMapGroupResponse consumerMapGroupResponse = new ConsumerMapGroupResponse();
        if (StringUtils.isEmpty(zoomMap.getOrDefault(level, ""))) {
            consumerMapGroupResponse.setLevel(level);
            consumerMapGroupResponse.setList(new ArrayList<>());
            return consumerMapGroupResponse;
        }

        List<String> cityCodes = new ArrayList<>();
        for (ConsumerLocationGroupItemVO item:itemVOList) {
            if( !cityCodes.contains(item.getCitycode()) ){
                cityCodes.add(item.getCitycode());
            }
        }

        //获取行政区信息
        Map<String,AdInfoDTO> allAdInfo = new HashMap<>();
        FieldTemplate fieldTemplate = fieldTemplateMapper.getTypeBySpId(spId);
        if( FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ){
            allAdInfo = functionAreaService.getFuncAreaMapByCode();
        }else if( cityCodes.size()>0 ){
            for (String cityCode:cityCodes) {
                Map<String,AdInfoDTO> adInfoMap = consumerLocationService.getCityAdInfo(cityCode);
                allAdInfo.putAll(adInfoMap);
            }
        }

        Map<String,FuncArea> pFuncAreaMap = getPFunAreaMap(level);

        //遍历数据处理
        String key = "";
        List<ConsumerMapGroupItemResponse> list = new ArrayList<>();
        for (ConsumerLocationGroupItemVO itemVO: itemVOList) {
            ConsumerMapGroupItemResponse groupItemResponse = new ConsumerMapGroupItemResponse();
            groupItemResponse.setCount(itemVO.getCnt());

            if( FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ) {
                if ("city".equals(level)) {
                    key = itemVO.getCitycode();
                    groupItemResponse.setAdCode(itemVO.getCitycode());
                } else if ("district".equals(level)) {
                    key = itemVO.getAdcode();
                    groupItemResponse.setAdCode(itemVO.getAdcode());
                    if (pFuncAreaMap.containsKey(itemVO.getAdcode())){
                        groupItemResponse.setPAdCode(pFuncAreaMap.get(itemVO.getAdcode()).getFuncCode());
                        groupItemResponse.setPAdName(pFuncAreaMap.get(itemVO.getAdcode()).getFuncName());
                    }
                } else {//street
                    key = itemVO.getTowncode();
                    groupItemResponse.setAdCode(itemVO.getTowncode());
                    if (pFuncAreaMap.containsKey(itemVO.getAdcode())){
                        groupItemResponse.setPAdCode(pFuncAreaMap.get(itemVO.getAdcode()).getFuncCode());
                        groupItemResponse.setPAdName(pFuncAreaMap.get(itemVO.getAdcode()).getFuncName());
                    }
                }
            }else{
                if( "city".equals(level) ){
                    key = itemVO.getCitycode();
                    groupItemResponse.setAdCode(itemVO.getCitycode());
                }else if ("district".equals(level)){
                    key = itemVO.getCitycode() + "_" + itemVO.getAdcode();
                    groupItemResponse.setAdCode(itemVO.getAdcode());
                }else {//street
                    key = itemVO.getCitycode() + "_" + itemVO.getAdcode() + "_" + itemVO.getTowncode();
                    groupItemResponse.setAdCode(itemVO.getTowncode());
                }
            }
            String center = "";
            if( allAdInfo.containsKey(key) ){
                AdInfoDTO adInfoDTO = allAdInfo.get(key);
                center = adInfoDTO.getCenter();
                if( FUNC_AREA_ALLOCAT_CUSTOM.equals(fieldTemplate.getFuncAreaAllocat()) ){
                    if ( (org.apache.commons.lang.StringUtils.isEmpty(center)  || !center.contains(",")) &&
                            null != itemVO.getLng() && null != itemVO.getLat()) {
                        center = itemVO.getLng()+","+itemVO.getLat();
                    }
                }else {
                    if ("street".equals(level) && null != itemVO.getLng() && null != itemVO.getLat()) {
                        center = itemVO.getLng()+","+itemVO.getLat();
                    }
                }
                if( org.apache.commons.lang.StringUtils.isNotEmpty(center) && center.contains(",") ){
                    groupItemResponse.setLngLat(center.split(","));
                }
                groupItemResponse.setLevel(allAdInfo.get(key).getLevel());
                groupItemResponse.setFence(adInfoDTO.getFence());
                groupItemResponse.setAdName(allAdInfo.get(key).getName());
                list.add(groupItemResponse);
            }
        }

        consumerMapGroupResponse.setLevel(level);
        consumerMapGroupResponse.setList(list);
        return consumerMapGroupResponse;
    }

    /**
     * 获取父级区域
     * @param level
     * @return
     */
    private Map<String,FuncArea> getPFunAreaMap(String level){
        Map<String, FuncArea> result = new HashMap<>();
        if ("city".equals(level)) {
            return result;
        }
        Map<String,FuncArea> funcAreaMap = new HashMap<>();
        Map<Integer,FuncArea> pFuncAreaMap = new HashMap<>();
        if ( "district".equals(level) ){
            funcAreaMap = functionAreaService.getFuncAreaMapByCode(2);
            pFuncAreaMap = functionAreaService.getFuncAreaMapById(1);
        }else if ("street".equals(level)){
            funcAreaMap = functionAreaService.getFuncAreaMapByCode(3);
            pFuncAreaMap = functionAreaService.getFuncAreaMapById(2);
        }
        for (String funcCode:funcAreaMap.keySet()){
            result.put(funcCode,pFuncAreaMap.get(funcAreaMap.get(funcCode).getPid()));
        }
        return result;
    }

    @Override
    public ConsumerMapResponse queryBoundaryCustList(IndustryConsumerMapRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);

        ConsumerMapResponse consumerMapResponse = new ConsumerMapResponse();
        List<ConsumerMapItemResponse> list = new ArrayList<>();
        List<ConsumerLocationItemVO> locationItemVOS = new ArrayList<>();
        String nELatLng = request.getNorthEastLatLng();
        String sWLatLng = request.getSouthWestLatLng();
        String polygon = null;
        if( org.apache.commons.lang.StringUtils.isNotEmpty(nELatLng) && org.apache.commons.lang.StringUtils.isNotEmpty(sWLatLng) ){
            String[] nELatLngArr = nELatLng.split(",");
            if( nELatLngArr.length!=2 ){
                throw new BizException("左上角经纬度不合法");
            }
            String[] sWLatLngArr = sWLatLng.split(",");
            if( sWLatLngArr.length!=2 ){
                throw new BizException("右下角经纬度不合法");
            }
//            if (request.getState() == 1) {
//                nELatLngArr = CoordinatesTransitionUtil.bd_decrypt(Double.valueOf(nELatLngArr[0]), Double.valueOf(nELatLngArr[1]));
//                sWLatLngArr = CoordinatesTransitionUtil.bd_decrypt(Double.valueOf(sWLatLngArr[0]), Double.valueOf(sWLatLngArr[1]));
//            }
            String boundary = nELatLngArr[0]+" "+nELatLngArr[1]+","+nELatLngArr[0]+" "+sWLatLngArr[1]+","
                    +sWLatLngArr[0]+" "+sWLatLngArr[1]+","+sWLatLngArr[0]+" "+nELatLngArr[1]+","
                    +nELatLngArr[0]+" "+nELatLngArr[1];
            polygon = "POLYGON(("+boundary+"))";
            log.info("nELatLng:{},sWLatLng:{}，polygon:{}",nELatLng,sWLatLng,polygon);
        }
        locationItemVOS = dtuMapper.queryConsumerLocationList(spIds, request.getIndustryType(), request.getAdCode(), request.getTownCode(), request.getBusinessAreaCode(),
                userFuncCodePermission.getFuncCodes(), polygon);

        for (ConsumerLocationItemVO consumerLocationItemVO: locationItemVOS) {
            ConsumerMapItemResponse response = new ConsumerMapItemResponse();
            BeanUtils.copyProperties(consumerLocationItemVO,response);
//            if (response.getPositionLat() > 0 && response.getPositionLon() > 0) {
//                if (request.getState() == 1) {
//                    double[] bdEncrypts = CoordinatesTransitionUtil.bdEncrypts(response.getPositionLon(), response.getPositionLat());
//                    response.setPositionLon(bdEncrypts[0]);
//                    response.setPositionLat(bdEncrypts[1]);
//                }
//            }
            response.setId(consumerLocationItemVO.getConsumerId());
            response.setStatusAnybroken(false);
            response.setStatusAnyalert(false);
            response.setStatusAnyoffline(false);
            response.setStatusAnynormal(true);
            if(consumerLocationItemVO.getBrokenNum()>0){
                response.setStatusAnybroken(true);
            }
            if(consumerLocationItemVO.getAlertNum()>0){
                response.setStatusAnyalert(true);
            }
            if(consumerLocationItemVO.getOfflineNum()>0){
                response.setStatusAnyoffline(true);
            }
            if(consumerLocationItemVO.getDeviceNum() > 0 &&
                    consumerLocationItemVO.getOfflineNum().equals(consumerLocationItemVO.getDeviceNum())){
                response.setStatusAnynormal(false);
            }else{
                response.setStatusAnynormal(false);
            }
            list.add(response);
        }
        consumerMapResponse.setList(list);
        return consumerMapResponse;
    }

    @Override
    public List<IndustryConsumerResponse> warningInfoGas(IndustryScreenWarningReq warningReq) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        //字典转换
        //List<DictionaryItemRespDTO> equipmentManufacturerDTOList = holder.getDictionaryByKey(Constants.MANUFACTURER_CODE);
        //设备厂商名称
        ConsoleSkSupplierListResponse responsea = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", responsea);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (responsea != null && responsea.getCode() == 0 && responsea.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(responsea.getData())) {
            supplierListVos = responsea.getData();
        }

        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        IndustryScreenWarningVo vo = new IndustryScreenWarningVo();
        vo.setIndustryType(warningReq.getIndustryType());
        vo.setAdCode(warningReq.getAdCode());
        vo.setTownCode(warningReq.getTownCode());
        vo.setBusinessAreaCode(warningReq.getBusinessAreaCode());
        vo.setSpIds(spIds);
        vo.setPage(1);
        vo.setPageSize(30);
        vo.setApplyStatus(warningReq.getApplyStatus());
        vo.setCustInfo(warningReq.getCustInfo());
        vo.setDeviceType(warningReq.getDeviceType());
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        vo.setFuncCodes(userFuncCodePermission.getFuncCodes());

        List<IndustryConsumerResponse> responseList = new ArrayList<>();
        List<DictionaryItemRespDTO> dictionary = holder.getIndustryTypeZJ();
        Map<String, String> dictionaryMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(dictionary)) {
            dictionaryMap = dictionary.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getValue, DictionaryItemRespDTO::getName, (a1, a2) -> a2));
        }
        if (warningReq.getDataType() == 0 || warningReq.getDataType() == 1) {
            //报警信息
            List<HistoryAlarmVo> alarmVoList = historyAlarmMapper.warningInfoGas(vo);
            log.info("warningInfoGas-alarmVoList:{}",JSONObject.toJSONString(alarmVoList));
            //获取所有imei号, 判断这些设备是否具有 接收器/电磁阀
            //List<ReceiverValve> alarmValveList = new ArrayList<>();
            List<Integer> consumerIds = new ArrayList<>();
            //Map<Integer, List<Contacts>> contactsMap =new HashMap<>();
            Map<Integer, List<Dtu>> dtuMap = new HashMap<>();
            Map<Integer, List<HistoryAlarm>> historyAlarmMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(alarmVoList)){
                alarmVoList.forEach(historyAlarmVo -> consumerIds.add(historyAlarmVo.getConsumerId()));
            }
            if (!CollectionUtils.isEmpty(consumerIds)){
                QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                dtuQueryWrapper.lambda().eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                        .ne(Dtu::getEquipmentType, "home_gas_detector")
                        .in(Dtu::getConsumerId,consumerIds);
                List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
                if (!CollectionUtils.isEmpty(dtuList)) {
                     dtuMap = dtuList.stream().collect(Collectors.groupingBy(Dtu::getConsumerId));
                }
                QueryWrapper<HistoryAlarm> alarmQueryWrapper = new QueryWrapper<>();
                alarmQueryWrapper.lambda().eq(HistoryAlarm::getIsDeleted, IS_DELETED_FALSE)
                        .in(HistoryAlarm::getConsumerId,consumerIds)
                        .in(HistoryAlarm::getAppealStatus, 0,1)
                        .orderByDesc(HistoryAlarm::getDeviceStatus, HistoryAlarm::getConcentration);
                List<HistoryAlarm> historyAlarms = historyAlarmMapper.selectList(alarmQueryWrapper);
                if (!CollectionUtils.isEmpty(historyAlarms)) {
                    historyAlarmMap = historyAlarms.stream().collect(Collectors.groupingBy(HistoryAlarm::getConsumerId));
                }
            }
            for (HistoryAlarmVo historyAlarmVo : alarmVoList) {
                IndustryConsumerResponse consumerResponse = new IndustryConsumerResponse();
                consumerResponse.setLastTime(historyAlarmVo.getLatestTime());
                consumerResponse.setName(historyAlarmVo.getName());
                consumerResponse.setId(historyAlarmVo.getConsumerId());
                consumerResponse.setSubsCode(historyAlarmVo.getSubsCode());
                consumerResponse.setCustName(historyAlarmVo.getCustName());
                consumerResponse.setCustAddress(historyAlarmVo.getCustAddress());
                consumerResponse.setMemberId(historyAlarmVo.getMemberId());
                consumerResponse.setPhone(historyAlarmVo.getPhone());
                consumerResponse.setCustPhone(historyAlarmVo.getCustPhone());
                consumerResponse.setSubsCodeName(consumerResponse.getCustName()+"("+consumerResponse.getSubsCode()+")");
                consumerResponse.setCustType(historyAlarmVo.getCustType());
                consumerResponse.setConsumerId(historyAlarmVo.getConsumerId());
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyAlarmVo.getOrgCode()) && orgSubsCodeMap.containsKey(historyAlarmVo.getOrgCode())) {
                    consumerResponse.setCompanyName(orgSubsCodeMap.get(historyAlarmVo.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyAlarmVo.getSpId())) {
                        consumerResponse.setCompanyName(companyNameMap.get(historyAlarmVo.getSpId()));
                    }
                }
                if (dtuMap.containsKey(historyAlarmVo.getConsumerId())) {
                    List<Dtu> dtuList = dtuMap.get(historyAlarmVo.getConsumerId());
                    consumerResponse.setDeviceSum(dtuList.size());
                    StringBuilder sb = new StringBuilder();
                    for (Dtu dtu : dtuList) {
                        if( !org.springframework.util.StringUtils.isEmpty(dtu.getEquipmentManufacturer()) ){
                            List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                                    dtu.getEquipmentManufacturer())).collect(Collectors.toList());
                            if(null!=listVos && !listVos.isEmpty()){
                                if (!sb.toString().contains(listVos.get(0).getMsName())) {
                                    sb.append(listVos.get(0).getMsName()).append(",");
                                }
                            }
                        }
                    }
                    if (sb.length() > 0) {
                        consumerResponse.setManufacturerName(sb.toString().substring(0, sb.length()-1));
                    }
                }
                if (historyAlarmMap.containsKey(historyAlarmVo.getLatestConsumerId())) {
                    List<HistoryAlarm> historyAlarms = historyAlarmMap.get(historyAlarmVo.getLatestConsumerId());
                    if (!CollectionUtils.isEmpty(historyAlarms)) {
                        consumerResponse.setConcentration(0);
                        consumerResponse.setBizType(2);
                        for (HistoryAlarm historyAlarm : historyAlarms) {
                            if (consumerResponse.getLastTime().before(historyAlarm.getCreatedAt())) {
                                consumerResponse.setLastTime(historyAlarm.getCreatedAt());
                            }
                        }
                        for (HistoryAlarm alarm : historyAlarms) {
                            //当包含3时取高报
                            if (alarm.getDeviceStatus() != null && alarm.getDeviceStatus() == 3) {
                                consumerResponse.setConcentration(alarm.getConcentration());
                                consumerResponse.setEquipmentStatus(alarm.getDeviceStatus());
                                consumerResponse.setXLEL(alarm.getConcentration()+"%LEL");
                                consumerResponse.setEquipmentStatusName("高报");
                                break;
                            }
                            //当没有高报包含2时取低报
                            if (alarm.getDeviceStatus() != null && alarm.getDeviceStatus() == 2) {
                                consumerResponse.setConcentration(alarm.getConcentration());
                                consumerResponse.setEquipmentStatus(alarm.getDeviceStatus());
                                consumerResponse.setXLEL(alarm.getConcentration()+"%LEL");
                                consumerResponse.setEquipmentStatusName("低报");
                                break;
                            }
                            //否则为紫荆的报警
                            if (consumerResponse.getConcentration() < alarm.getConcentration()) {
                                consumerResponse.setConcentration(alarm.getConcentration());
                                consumerResponse.setEquipmentStatus(alarm.getDeviceStatus());
                                consumerResponse.setXLEL(alarm.getConcentration()+"%LEL");
                                consumerResponse.setEquipmentStatusName("报警");
                            }
                        }
                    }
                }
                consumerResponse.setAlarmDevice(historyAlarmVo.getAlarmSum());
                if (dictionaryMap.containsKey(historyAlarmVo.getIndustryType())) {
                    consumerResponse.setIndustryTypeName(dictionaryMap.get(historyAlarmVo.getIndustryType()));
                }
                responseList.add(consumerResponse);
            }
        }
        if (warningReq.getDataType() ==0 || warningReq.getDataType() ==2){
            //故障信息
            //获取所有imei号, 判断这些设备是否具有 接收器/电磁阀
            List<HistoryBrokenVO> brokenVOList = historyBrokenMapper.warningInfoGas(vo);
            log.info("warningInfoAsst-brokenVOList:{}",JSONObject.toJSONString(brokenVOList));
            List<Integer> consumerIds = new ArrayList<>();
           // Map<Integer, List<Contacts>> contactsMap =new HashMap<>();
            Map<Integer, List<Dtu>> dtuMap = new HashMap<>();
            Map<Integer, List<HistoryBroken>> historyBrokenMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(brokenVOList))
                //brokenVOList.forEach(historyAlarmVo -> consumerIds.add(historyAlarmVo.getConsumerId()));
                brokenVOList.forEach(historyAlarmVo -> consumerIds.add(historyAlarmVo.getConsumerId()));
            log.info("warningInfoAsst-consumerIds:{}",JSONObject.toJSONString(consumerIds));
            if (!CollectionUtils.isEmpty(consumerIds)){
                QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
                dtuQueryWrapper.lambda().eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                        .in(Dtu::getConsumerId,consumerIds);
                List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
                if (!CollectionUtils.isEmpty(dtuList)) {
                    dtuMap = dtuList.stream().collect(Collectors.groupingBy(Dtu::getConsumerId));
                }

                QueryWrapper<HistoryBroken> alarmQueryWrapper = new QueryWrapper<>();
                alarmQueryWrapper.lambda().eq(HistoryBroken::getIsDeleted, IS_DELETED_FALSE)
                        .in(HistoryBroken::getConsumerId,consumerIds)
                        .in(HistoryBroken::getAppealStatus, 0,1)
                        .orderByDesc(HistoryBroken::getCreatedAt);
                List<HistoryBroken> historyBrokens = historyBrokenMapper.selectList(alarmQueryWrapper);
                if (!CollectionUtils.isEmpty(historyBrokens)) {
                    historyBrokenMap = historyBrokens.stream().collect(Collectors.groupingBy(HistoryBroken::getConsumerId));
                }
            }

            for (HistoryBrokenVO historyBrokenVO : brokenVOList) {

                IndustryConsumerResponse consumerResponse = new IndustryConsumerResponse();
                if (StringUtils.isEmpty(historyBrokenVO.getBrokenReason())) {
                    consumerResponse.setBrokenReason("电磁阀故障");
                } else {
                    if (historyBrokenVO.getBrokenReason().contains(";")) {
                        consumerResponse.setBrokenReason(historyBrokenVO.getBrokenReason().split(";")[0]);
                    } else {
                        consumerResponse.setBrokenReason(historyBrokenVO.getBrokenReason());
                    }
                }
                consumerResponse.setLastTime(historyBrokenVO.getLatestTime());
                consumerResponse.setName(historyBrokenVO.getName());
                consumerResponse.setId(historyBrokenVO.getConsumerId());
                consumerResponse.setSubsCode(historyBrokenVO.getSubsCode());
                consumerResponse.setCustName(historyBrokenVO.getCustName());
                consumerResponse.setCustAddress(historyBrokenVO.getCustAddress());
                consumerResponse.setMemberId(historyBrokenVO.getMemberId());
                consumerResponse.setPhone(historyBrokenVO.getPhone());
                consumerResponse.setCustPhone(historyBrokenVO.getCustPhone());
                consumerResponse.setCustType(historyBrokenVO.getCustType());
                consumerResponse.setSubsCodeName(consumerResponse.getCustName()+"("+consumerResponse.getSubsCode()+")");
                consumerResponse.setConsumerId(historyBrokenVO.getConsumerId());
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyBrokenVO.getOrgCode()) && orgSubsCodeMap.containsKey(historyBrokenVO.getOrgCode())) {
                    consumerResponse.setCompanyName(orgSubsCodeMap.get(historyBrokenVO.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyBrokenVO.getSpId())) {
                        consumerResponse.setCompanyName(companyNameMap.get(historyBrokenVO.getSpId()));
                    }
                }
                if (dtuMap.containsKey(historyBrokenVO.getConsumerId())) {
                    List<Dtu> dtuList = dtuMap.get(historyBrokenVO.getConsumerId());
                    consumerResponse.setDeviceSum(dtuList.size());
                    StringBuilder sb = new StringBuilder();
                    for (Dtu dtu : dtuList) {
                        if( !org.springframework.util.StringUtils.isEmpty(dtu.getEquipmentManufacturer()) ){
                            List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                                    dtu.getEquipmentManufacturer())).collect(Collectors.toList());
                            if(null!=listVos && !listVos.isEmpty()){
                                if (!sb.toString().contains(listVos.get(0).getMsName())) {
                                    sb.append(listVos.get(0).getMsName()).append(",");
                                }
                            }
                        }
                    }
                    if (sb.length() > 0) {
                        consumerResponse.setManufacturerName(sb.toString().substring(0, sb.length()-1));
                    }
                }
                if (historyBrokenMap.containsKey(historyBrokenVO.getConsumerId())) {
                    consumerResponse.setLastTime(historyBrokenMap.get(historyBrokenVO.getConsumerId()).get(0).getCreatedAt());
                }
                consumerResponse.setAlarmDevice(historyBrokenVO.getAlarmSum());
                if (dictionaryMap.containsKey(historyBrokenVO.getIndustryType())){
                    consumerResponse.setIndustryTypeName(dictionaryMap.get(historyBrokenVO.getIndustryType()));
                }
                consumerResponse.setEquipmentStatus(4);
                consumerResponse.setBizType(3);
                consumerResponse.setXLEL(historyBrokenVO.getConcentration()+"%LEL");
                consumerResponse.setEquipmentStatusName(DeviceStatusEnum.parse(4).getName());
                responseList.add(consumerResponse);
            }
        }
        log.info("warningInfoGas-responseList：{}",JSONObject.toJSON(responseList));
        //取列表时间倒序30条
        responseList.sort((t1,t2) -> t2.getLastTime().compareTo(t1.getLastTime()));
        int size = responseList.size();
        int end = 30;
        if ( size < 30) end = size;
        List<IndustryConsumerResponse> data = responseList.subList(0, end);
        return data;
    }

    @Override
    public PageUtil<IndustryUnderUserListVo> underUserList(IndustryUnderUserListReq userListReq) {
        String spId = ApplicationUtils.getWorkingSpId();
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spId,ApplicationUtils.getUserId());
        userListReq.setSpId(spId);
        //用户总数
        Integer total = consumerMapper.getUnderUserSum(spId, userListReq.getIndustryType(), userListReq.getAdCode(), userListReq.getTownCode(), userListReq.getBusinessAreaCode(),
                userFuncCodePermission.getFuncCodes());
        int start = (userListReq.getPage() - 1) * userListReq.getPageSize();
        List<IndustryUnderUserListVo> userListVos = consumerMapper.underUserList(spId, userListReq.getIndustryType(), userListReq.getAdCode(), userListReq.getTownCode(), userListReq.getBusinessAreaCode(), start, userListReq.getPageSize(),
                userFuncCodePermission.getFuncCodes());
        if (!CollectionUtils.isEmpty(userListVos)) {
            //客户字典
            List<DictionaryItemRespDTO> dictionary = holder.getDictionaryByKey(INDUSTRY_TYPE_CODE);
            List<Integer> consumerId = new ArrayList<>();

            // 序号 serialNum = (userListReq.getPage() - 1) * userListReq.getPageSize() +1
            int serialNum = start + 1;

            for (IndustryUnderUserListVo userListVo : userListVos) {
                userListVo.setSerialNum(serialNum++);
                DictionaryItemRespDTO equipmentTypeDTO = dictionary.stream()
                        .filter(d -> d.getValue().equals(userListVo.getIndustryType()))
                        .collect(Collectors.toList()).get(0);
                userListVo.setIndustryTypeName(equipmentTypeDTO.getName());
                consumerId.add(userListVo.getConsumerId());
                StringBuilder sb = new StringBuilder();
                if (!StringUtils.isEmpty(userListVo.getCity())) {
                    sb.append(userListVo.getCity()).append(" ");
                }
                if (!StringUtils.isEmpty(userListVo.getDistrict())) {
                    sb.append(userListVo.getDistrict()).append(" ");
                }
                if (!StringUtils.isEmpty(userListVo.getTownship())) {
                    sb.append(userListVo.getTownship()).append(" ");
                }
                if (sb.length() > 0) {
                    userListVo.setFuncArea(sb.toString());
                }
            }
            //根据客户id批量查询设备
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().in(Dtu::getConsumerId, consumerId)
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Dtu::getSpId, spId)
                    .ne(Dtu::getEquipmentType, "home_gas_detector");
            List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
            Map<Integer, Map<String, List<Dtu>>> dtuMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(dtuList)) {
                dtuMap = dtuList.stream().collect(Collectors.groupingBy(Dtu::getConsumerId,Collectors.groupingBy(Dtu::getEquipmentType)));
            }
            for (IndustryUnderUserListVo userListVo : userListVos) {
                if (dtuMap.containsKey(userListVo.getConsumerId())) {
//                    userListVo.setDeviceSum(dtuMap.get(userListVo.getConsumerId()).size());
                    Map<String, List<Dtu>> equipmentTypeMap = dtuMap.get(userListVo.getConsumerId());
                    if (MapUtils.isNotEmpty(equipmentTypeMap)) {
                        int controlSum = 0,probeSum = 0;
                        if (equipmentTypeMap.containsKey(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                            controlSum = equipmentTypeMap.get(EquipmentType.GAS_ALARM_CONTROLLER.getCode()).size();
                        }
                        if (equipmentTypeMap.containsKey(EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode())) {
                            controlSum += equipmentTypeMap.get(EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode()).size();
                        }
                        if (equipmentTypeMap.containsKey(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
                            probeSum = equipmentTypeMap.get(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode()).size();
                        }
                        userListVo.setControlSum(controlSum);
                        userListVo.setProbeSum(probeSum);
                    } else {
                        userListVo.setControlSum(0);
                        userListVo.setProbeSum(0);
                    }
                } else {
                    userListVo.setDeviceSum(0);
                    userListVo.setControlSum(0);
                    userListVo.setProbeSum(0);
                }
            }
        }
        PageUtil<IndustryUnderUserListVo> pageInfo = new PageUtil<>(userListReq.getPage(), userListReq.getPageSize(), total, userListVos);
        log.info("用户接入列表：" + userListVos.toString());
        return pageInfo;
    }

    @Override
    public ConsumerDetailResponse consumerDetailGas(CustDetailRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //本身以及下级spid
        List<String> spIds = organizationService.getSpIds(spId);

        String consumerId = request.getConsumerId();
        ConsumerDetailResponse consumerDetailResponse = new ConsumerDetailResponse();
        //判断该客户是否存在
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getId, consumerId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Consumer::getSpId, spIds);
        Consumer consumer = consumerService.getOne(consumerWrapper);
        if (consumer == null) {
            throw new BizException("该客户id不存在!");
        }
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        ConsumerResponse consumerResponse = new ConsumerResponse();
        BeanUtil.copyProperties(consumer, consumerResponse);
        //客户字典
        List<DictionaryItemRespDTO> dictionary = holder.getIndustryTypeZJ();
        for (DictionaryItemRespDTO dto : dictionary) {
            if (dto.getValue().equals(consumer.getIndustryType())) consumerResponse.setIndustryTypeName(dto.getName());
        }
        log.info("客户基本信息:{}", consumer.toString());

        List<Integer> consumerIds = new ArrayList<>();
        consumerIds.add(Integer.parseInt(consumerId));
        List<Contacts> contacts=consumerMapper.selectLevelContactsByConsumerId(consumerIds);
        if (!CollectionUtils.isEmpty(contacts)){
            String telephone = contacts.get(0).getTelephone();
            consumerResponse.setLevelPhone(telephone);
        }
        consumerResponse.setName(consumer.getName());
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(consumer.getOrgCode()) && orgSubsCodeMap.containsKey(consumer.getOrgCode())) {
            consumerResponse.setCompanyName(orgSubsCodeMap.get(consumer.getOrgCode()));
        } else {
            if (companyNameMap.containsKey(consumer.getSpId())) {
                consumerResponse.setCompanyName(companyNameMap.get(consumer.getSpId()));
            }
        }
        //客户的设备状态
        consumerResponse.setStatusAnyalert(false);
        consumerResponse.setStatusAnybroken(false);
        consumerResponse.setStatusAnyoffline(false);
        consumerResponse.setStatusAnynormal(true);
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getConsumerId, consumer.getId())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Dtu::getSpId, spIds)
                .ne(Dtu::getEquipmentType, "home_gas_detector");
        List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
        //字典转换
        //List<DictionaryItemRespDTO> equipmentManufacturerDTOList = holder.getDictionaryByKey(Constants.MANUFACTURER_CODE);
        //设备厂商名称
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
        }
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        List<ConsumerEquipmentResponse> equipmentVOList = new ArrayList<>();

        //查询设备信息,用户状态, 得到全量设备信息
        int sum = 0;
        for (Dtu dtu : dtuList) {
            log.info("设备："+dtu.toString());
            LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
            //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
            if (latestLog.getEquipmentStatus().equals(0)) {
                consumerResponse.setStatusAnyoffline(true);
                sum++;
            } else if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3) ||
                    latestLog.getEquipmentStatus().equals(6)) {
                consumerResponse.setStatusAnyalert(true);
            } else if (latestLog.getEquipmentStatus().equals(4)) {
                consumerResponse.setStatusAnybroken(true);
            }

            ConsumerEquipmentResponse vo = new ConsumerEquipmentResponse();
            BeanUtils.copyProperties(dtu, vo);
            vo.setEquipmentName(dtu.getName());
            vo.setEquipmentId(dtu.getDeviceCode());
            vo.setEquipmentTypeCode(dtu.getEquipmentType());
            vo.setValueExist(dtu.getValveInfoId()==0?1:0);
            vo.setHasValve(dtu.getValveInfoId()==0?"-":"有");
            DictionaryItemRespDTO equipmentTypeDTO = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(dtu.getEquipmentType()))
                    .collect(Collectors.toList()).get(0);
            List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                    dtu.getEquipmentManufacturer())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(listVos)) {
                vo.setEquipmentManufacturer(listVos.get(0).getMsName());
                vo.setEquipmentModelMa(dtu.getEquipmentModel()+"("+listVos.get(0).getMsName()+")");
            } else {
                vo.setEquipmentModelMa(dtu.getEquipmentModel());
            }
            vo.setEquipmentType(equipmentTypeDTO.getName());
            vo.setEquipmentModel(dtu.getEquipmentModel());
            vo.setEquipmentStatus(latestLog.getEquipmentStatus());
            vo.setEquipmentStatusName(DeviceStatusEnum.parse(latestLog.getEquipmentStatus()).getName()); //设备状态
            //报警状态 需要附带浓度
            if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3) || latestLog.getEquipmentStatus().equals(6)) {
                latestLog.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo() + "(" + latestLog.getXlel() + ")");
            }
            vo.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo());
            vo.setEquipmentStatusAndInfo(vo.getEquipmentStatus()+"("+latestLog.getEquipmentStatusInfo()+")");
            if (latestLog.getValveStatus()!=null)
                vo.setValveStatus(ValveStatusEnum.parse(latestLog.getValveStatus()).getName());
            if (latestLog.getReceiverStatus()!=null) vo.setReceiverStatus(latestLog.getReceiverStatus()==0?"离线":"正常");
            //紫荆wifi报警的状态信息
            if ( Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom()) ) {
                LambdaQueryWrapper<ReceiverValve> lqw = new LambdaQueryWrapper<>();
                lqw.eq(ReceiverValve::getDeviceId, dtu.getIMEI()).in(ReceiverValve::getSpId, spIds)
                        .eq(ReceiverValve::getIsDeleted, Constants.IS_DELETED_FALSE);
                ReceiverValve receiverValve = receiverValveService.getOne(lqw);
                if (receiverValve != null) {
                    vo.setWithReceiver(true);
                    vo.setReceiverStatus(receiverValve.getReceiverStatus()==0?"离线":"正常");
                    if (receiverValve.getBrokenStatus() == VALVE_WORK_STATUS_BROKEN){
                        vo.setValveStatus(ValveStatusEnum.parse(2).getName());
                    }else {
                        vo.setValveStatus(ValveStatusEnum.parse(receiverValve.getValveStatus()).getName());
                    }
                    vo.setBrokenInfo(receiverValve.getBrokenStatusInfo());
                }else{
                    vo.setWithReceiver(false);
                }
            }
            log.info("紫荆设备："+vo.toString());
            equipmentVOList.add(vo);
        }
        if (sum == dtuList.size()) {
            consumerResponse.setStatusAnynormal(false);
        }

        List<ConsumerEquipmentResponse> responseList = cockpitService.equipmentListByStatus(consumerResponse, equipmentVOList);
        log.info("设备列表："+responseList.toString());
        //数据合并
        consumerDetailResponse.setConsumerResponse(consumerResponse);
        consumerDetailResponse.setConsumerEquipmentResponseList(responseList);

        return consumerDetailResponse;
    }

    @Override
    public Map<String, Integer> getConditionSum(IndustryScreenWarningReq warningReq) {
        Map<String, Integer> resultMap = new HashMap<>();
        Map<String, Integer> conditionAlarm = null;
        Map<String, Integer> conditionBroken = null;
        try {
            if (warningReq.getDataType() == 0 || warningReq.getDataType() == 1) {
                conditionAlarm = getAlarmConditionList(0, warningReq.getIndustryType(), warningReq.getAdCode(), warningReq.getTownCode(), warningReq.getBusinessAreaCode(), warningReq.getDeviceType());
                log.info("getConditionList-conditionAlarm:{}", JSONObject.toJSON(conditionAlarm));
            }
            if (warningReq.getDataType() == 0 || warningReq.getDataType() == 2) {
                conditionBroken = getBrokenConditionList(warningReq.getIndustryType(), warningReq.getAdCode(), warningReq.getTownCode(), warningReq.getBusinessAreaCode(), warningReq.getDeviceType());
            }
            log.info("getConditionList-conditionBroken:{}",JSONObject.toJSON(conditionBroken));
            Integer alarm = conditionAlarm.get("未处理")==null?0:conditionAlarm.get("未处理");
            Integer broken = conditionBroken.get("未处理")==null?0:conditionBroken.get("未处理");
            resultMap.put("undisposed",alarm+broken);
        } catch (Exception e) {
            log.error("getConditionSum-error:{}",e);
            resultMap.put("undisposed",0);
        }
        log.info("getConditionList-resultMap:{}",JSONObject.toJSON(resultMap));
        return resultMap;
    }

    @Override
    public Map<String, Integer> warningSum(IndustryScreenWarningReq warningReq) {
        Map<String, Integer> warningSumMap = new HashMap<>();
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        IndustryScreenWarningVo vo = new IndustryScreenWarningVo();
        vo.setIndustryType(warningReq.getIndustryType());
        vo.setAdCode(warningReq.getAdCode());
        vo.setTownCode(warningReq.getTownCode());
        vo.setBusinessAreaCode(warningReq.getBusinessAreaCode());
        vo.setSpIds(spIds);
        vo.setApplyStatus(warningReq.getApplyStatus());
        vo.setCustInfo(warningReq.getCustInfo());
        vo.setDeviceType(warningReq.getDeviceType());
        List<HistoryAlarmVo> alarmVoList = historyAlarmMapper.warningInfoGas(vo);
        //报警数量
        warningSumMap.put("alarmSum", alarmVoList.size());
        List<HistoryBrokenVO> brokenVOList = historyBrokenMapper.warningInfoGas(vo);
        //故障数量
        warningSumMap.put("brokenSum", brokenVOList.size());
        //总量
        warningSumMap.put("allSum", alarmVoList.size() + brokenVOList.size());
        return warningSumMap;
    }

    @Override
    public ConsumerDeviceDetailResp consumerDeviceDetail(CustDetailRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //本身以及下级spid
        List<String> spIds = organizationService.getSpIds(spId);

        String consumerId = request.getConsumerId();
        ConsumerDeviceDetailResp consumerDetailResponse = new ConsumerDeviceDetailResp();
        //判断该客户是否存在
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getId, consumerId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Consumer::getSpId, spIds);
        Consumer consumer = consumerService.getOne(consumerWrapper);
        if (consumer == null) {
            throw new BizException("该客户id不存在!");
        }
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        IndustryConsumerResponse consumerResponse = new IndustryConsumerResponse();
        BeanUtil.copyProperties(consumer, consumerResponse);
        //客户字典
        List<DictionaryItemRespDTO> dictionary = holder.getIndustryTypeZJ();
        for (DictionaryItemRespDTO dto : dictionary) {
            if (dto.getValue().equals(consumer.getIndustryType())) consumerResponse.setIndustryTypeName(dto.getName());
        }
        log.info("客户基本信息:{}", consumer.toString());

        List<Integer> consumerIds = new ArrayList<>();
        consumerIds.add(Integer.parseInt(consumerId));
        consumerResponse.setName(consumer.getName());
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(consumer.getOrgCode()) && orgSubsCodeMap.containsKey(consumer.getOrgCode())) {
            consumerResponse.setCompanyName(orgSubsCodeMap.get(consumer.getOrgCode()));
        } else {
            if (companyNameMap.containsKey(consumer.getSpId())) {
                consumerResponse.setCompanyName(companyNameMap.get(consumer.getSpId()));
            }
        }
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getConsumerId, consumer.getId())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Dtu::getSpId, spIds)
                .ne(Dtu::getEquipmentType, "home_gas_detector");
        List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
        //字典转换
        List<DictionaryItemRespDTO> equipmentManufacturerDTOList = holder.getDictionaryByKey(Constants.MANUFACTURER_CODE);
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        List<ConsumerEquipmentResp> equipmentVOList = new ArrayList<>();

        //查询设备信息,用户状态, 得到全量设备信息
        if (!CollectionUtils.isEmpty(dtuList)) {
            List<ConsumerEquipmentResp> equipmentRespList = new ArrayList<>();
            for (Dtu dtu : dtuList) {
                log.info("设备："+dtu.toString());
                LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());

                ConsumerEquipmentResp vo = new ConsumerEquipmentResp();
                BeanUtils.copyProperties(dtu, vo);
                vo.setEquipmentName(dtu.getName());
                vo.setEquipmentId(dtu.getDeviceCode());
                vo.setEquipmentTypeCode(dtu.getEquipmentType());
                DictionaryItemRespDTO equipmentTypeDTO = equipmentTypeDTOList.stream()
                        .filter(d -> d.getValue().equals(dtu.getEquipmentType()))
                        .collect(Collectors.toList()).get(0);
                DictionaryItemRespDTO equipmentManufacturerDTO = equipmentManufacturerDTOList.stream()
                        .filter(d -> d.getValue().equals(dtu.getEquipmentManufacturer()))
                        .collect(Collectors.toList()).get(0);
                vo.setEquipmentType(equipmentTypeDTO.getName());
                vo.setEquipmentManufacturer(equipmentManufacturerDTO.getName());
                vo.setEquipmentModel(dtu.getEquipmentModel());
                vo.setEquipmentModelMa(dtu.getEquipmentModel()+"("+equipmentManufacturerDTO.getName()+")");
                vo.setEquipmentStatus(latestLog.getEquipmentStatus());
                vo.setEquipmentStatusName(DeviceStatusEnum.parse(latestLog.getEquipmentStatus()).getName()); //设备状态
                //报警状态 需要附带浓度
                if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3) || latestLog.getEquipmentStatus().equals(6)) {
                    latestLog.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo() + "(" + latestLog.getXlel() + ")");
                }
                log.info("紫荆设备："+vo.toString());
                equipmentRespList.add(vo);
            }
            //转为树形结构
            List<String> imeiList = new ArrayList<>();
            for (ConsumerEquipmentResp equipmentResp : equipmentRespList) {
                if (!equipmentResp.getIMEI().contains("-")) {
                    equipmentVOList.add(equipmentResp);
                    imeiList.add(equipmentResp.getIMEI());
                }
            }
            for (ConsumerEquipmentResp equipmentResp : equipmentRespList) {
                //根据是否带-划分到控制器下面
                if (equipmentResp.getIMEI().contains("-") && imeiList.contains(equipmentResp.getIMEI().split("-")[0])) {
                    String imei = equipmentResp.getIMEI().split("-")[0];
                    for (ConsumerEquipmentResp resp : equipmentVOList) {
                        if (resp.getIMEI().equals(imei)) {
                            List<ConsumerEquipmentResp> equipmentResps = resp.getChildren();
                            if (CollectionUtils.isEmpty(equipmentResps)) {
                                List<ConsumerEquipmentResp> respList = new ArrayList<>();
                                equipmentResp.setSeq(1);
                                respList.add(equipmentResp);
                                resp.setChildren(respList);
                            } else {
                                equipmentResp.setSeq(equipmentResps.size() + 1);
                                equipmentResps.add(equipmentResp);
                                resp.setChildren(equipmentResps);
                            }
                        }
                    }
                }
            }
        }
        log.info("设备列表："+equipmentVOList.toString());
        //数据合并
        consumerDetailResponse.setConsumerResponse(consumerResponse);
        consumerDetailResponse.setConsumerEquipmentResponseList(equipmentVOList);

        return consumerDetailResponse;
    }

    @Override
    public PageUtil<IndustryAlertLogResp> getAlarmList(IndustryRecordRequest req) {
        List<IndustryAlertLogResp> resultList = new ArrayList<>();
        //要最近的设备信息，从数据库里查询，
        LatestLogListVO vo = new LatestLogListVO();
        //1.查询条件封装
        vo.setConsumerId(Integer.valueOf(req.getConsumerId()));

        String spId = ApplicationUtils.getWorkingSpId();
        //1.1所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        vo.setSpIds(spIds);
        Map<String, String> reasonMap = new HashMap<>();
        try {
            List<DictionaryItemRespDTO> alarmReasonDict = holder.getDictionaryByKeyNoCache(
                    Constants.ALARM_REASON, spId);
            reasonMap = alarmReasonDict.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getValue, DictionaryItemRespDTO::getName));
        } catch(Exception e) {
            log.info("getAlarmList-alarmReasonDict-error:{}", e.getMessage());
        }
        Map<String, String> alarmReasonMap = reasonMap;

        Page<HistoryAlarmVo> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<HistoryAlarmVo> list = historyAlarmMapper.industryAlarmRecord(vo);
        if (!CollectionUtils.isEmpty(list)) {
            //设备类型名称
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKeys(
                    EquipmentType.DICT_CODE, spIds);
            //行业类型名称
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getIndustryTypeZJ(spIds);
            //设备厂商名称
            ConsoleSkSupplierListResponse supplierList = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", supplierList);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (supplierList != null && supplierList.getCode() == 0 && supplierList.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(supplierList.getData())) {
                supplierListVos = supplierList.getData();
            }

            List<AlarmSupplierListVo> finalSupplierListVos = supplierListVos;
            resultList = list.stream().map(historyAlarmVo -> {
                IndustryAlertLogResp response = new IndustryAlertLogResp();
                BeanUtils.copyProperties(historyAlarmVo, response);
                response.setValveInfoId(historyAlarmVo.getValveInfoId());
                response.setXlel(historyAlarmVo.getConcentration() + " %LEL");
                //处理状态
                response.setAppealStatusMsg(AppealStateEnum.matcher(historyAlarmVo.getAppealStatus()).getMsg());
                // 报警原因
                response.setValveBrokenInfo(alarmReasonMap.get(historyAlarmVo.getBrokenInfo()) == null ? Constants.BLANK : alarmReasonMap.get(historyAlarmVo.getBrokenInfo()));
                //设置设备类型名称
                response.setEquipmentTypeName(getName(equipmentTypeDictList, historyAlarmVo.getEquipmentType()));
                //设置行业类型名称
                response.setIndustryTypeName(getName(industryTypeDictList, historyAlarmVo.getIndustryType()));
                //设置设备厂商
                response.setEquipmentManufacturer(finalSupplierListVos.stream().filter(a->a.getAlarmSystemCode().equals(
                        historyAlarmVo.getEquipmentManufacturer())).collect(Collectors.toList()).get(0).getMsName());

                return response;
            }).collect(Collectors.toList());
        }
        log.info("getAlarmList-resultList:{}", JSONObject.toJSONString(resultList));
        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), resultList, null);
        return pageInfo;
    }

    @Override
    public PageUtil<IndustryBrokenLogResp> broken(IndustryRecordRequest req) {

        List<IndustryBrokenLogResp> resultList = new ArrayList<>();
        LatestLogListVO vo = new LatestLogListVO();
        //1.查询条件封装
        vo.setConsumerId(Integer.valueOf(req.getConsumerId()));

        String spId = ApplicationUtils.getWorkingSpId();
        //1.1所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        vo.setSpIds(spIds);
        Page<HistoryBrokenVO> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<HistoryBrokenVO> list = historyBrokenMapper.industryBorkenRecord(vo);
        if (!CollectionUtils.isEmpty(list)) {
            //设备类型列表
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKey(
                    EquipmentType.DICT_CODE);
            //行业类型列表
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getIndustryTypeZJ(spIds);
            //设备厂商列表
            ConsoleSkSupplierListResponse supplierList = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", supplierList);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (supplierList != null && supplierList.getCode() == 0 && supplierList.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(supplierList.getData())) {
                supplierListVos = supplierList.getData();
            }

            for (HistoryBrokenVO historyBrokenVO : list) {
                IndustryBrokenLogResp response = new IndustryBrokenLogResp();
                BeanUtils.copyProperties(historyBrokenVO, response);
                response.setValveInfoId(historyBrokenVO.getValveInfoId());
                //处理状态
                response.setAppealStatusMsg(AppealStateEnum.matcher(historyBrokenVO.getAppealStatus()).getMsg());
                //设置设备类型名称
                response.setEquipmentTypeName(getName(equipmentTypeDictList, historyBrokenVO.getEquipmentType()));
                //设置行业类型名称
                response.setIndustryTypeName(getName(industryTypeDictList, historyBrokenVO.getIndustryType()));
                //设置设备厂商
                List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                        historyBrokenVO.getEquipmentManufacturer())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(listVos)) {
                    response.setEquipmentManufacturer(listVos.get(0).getMsName());
                }
                //紫荆设备 故障原因、联系人手机号
                if (historyBrokenVO.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM) {
                    if (!StringUtils.isEmpty(historyBrokenVO.getBrokenReason())
                            && !StringUtils.isEmpty(historyBrokenVO.getBrokenInfo())) {
                        response.setBrokenReason(historyBrokenVO.getBrokenReason() + ";" + historyBrokenVO.getBrokenInfo());

                    } else if (StringUtils.isEmpty(historyBrokenVO.getBrokenReason())
                            && !StringUtils.isEmpty(historyBrokenVO.getBrokenInfo())) {
                        response.setBrokenReason(historyBrokenVO.getBrokenInfo());
                    }
                }
                resultList.add(response);
            }
        }
        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), resultList, null);
        return pageInfo;
    }

    public Map<String, Integer> getAlarmConditionList(Integer isSpecialized, String industryType, String adCode, String townCode, String businessAreaCode, Integer deviceType) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        Map<String, Integer> map = new HashMap<>();
        //诉求状态：0待处理 1工单处理中 2已处理 3工单处理完成
        GetCondtionListVo conditionList = dtuMapper.getAlarmConditionList(spIds, industryType, adCode, townCode, businessAreaCode, deviceType, userFuncCodePermission.getFuncCodes());
        Integer all = conditionList.getNumber();
        Integer handling = conditionList.getHandling();
        Integer hasHandled = conditionList.getHasHandled();
        Integer finishing = conditionList.getFinishing();
        Integer unclosed = conditionList.getUnclosed();
        Integer closed = conditionList.getClosed();
        Integer handleInstall = conditionList.getHandleInstall();
        Integer handlerTest = conditionList.getHandlerTest();
        Integer waitHandle = all - handling - hasHandled - finishing - unclosed - closed - handleInstall - handlerTest;
        if(isSpecialized == 1){
            map.put("待处理", waitHandle);
            map.put("未办结",unclosed);
            map.put("已办结", closed);
        }else {
            map.put("未处理", waitHandle);
            map.put("处理中", handling + unclosed);
            map.put("处理完成", hasHandled + finishing+closed + handleInstall + handlerTest);
        }
        return map;

    }

    public Map<String, Integer> getBrokenConditionList(String industryType, String adCode, String townCode, String businessAreaCode, Integer deviceType) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        Map<String, Integer> map = new HashMap<>();
        //诉求状态：0待处理 1工单处理中 2已处理 3工单处理完成
        GetCondtionListVo conditionList = dtuMapper.getBrokenConditionList(spIds, industryType, adCode, townCode, businessAreaCode, deviceType, userFuncCodePermission.getFuncCodes());
        Integer all = conditionList.getNumber();
        Integer handling = conditionList.getHandling();
        Integer hasHandled = conditionList.getHasHandled();
        Integer finishing = conditionList.getFinishing();
        Integer unclosed = conditionList.getUnclosed();
        Integer closed = conditionList.getClosed();
        Integer handleInstall = conditionList.getHandleInstall();
        Integer handlerTest = conditionList.getHandlerTest();
        Integer waitHandle = all - handling - hasHandled - finishing - unclosed - closed - handleInstall - handlerTest;

        map.put("未处理", waitHandle);
        map.put("处理中", handling);
        map.put("处理完成", hasHandled + finishing + closed + unclosed + handleInstall+ handlerTest);
        return map;

    }

    private String getName(List<DictionaryItemRespDTO> list, String  value) {
        if( !CollectionUtils.isEmpty(list)){
            List<DictionaryItemRespDTO> respDTOS = list.stream()
                    .filter(dict -> dict.getValue().equals(value)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(respDTOS)){
                return respDTOS.get(0).getName();
            }
        }
        return null;
    }

}
